package com.cachemanage.controller;

import com.cachemanage.pojo.Book;
import com.cachemanage.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Controller
public class BookController {
	@Resource
	BookService bookService;
	@GetMapping("/books")
	public String findAllBooks(Model model){
		List<Book> books = bookService.findAllBooks();
		model.addAttribute("books",books);
		return"books";
	}
	@GetMapping("/books/{id}")
	public String findBookById(@PathVariable Integer id,Model model){
		Book book = bookService.findBookById(id);
		model.addAttribute("book",book);
		return "book";
	}
	@PostMapping("/addBook")
	public String addBook(Book book){
		bookService.addBook(book);
		return "redirect:/books";
	}
	@GetMapping("/addBook")
	public String addBook(){
		return "addBook";
	}
	@GetMapping("/deleteBook/{id}")
	public String deleteById(@PathVariable Integer id){
		bookService.deleteBook(id);
		return "redirect:/books";
	}
	@GetMapping("/updateBook/{id}")
	public String  toUpdateBook(@PathVariable Integer id,Model model){
		model.addAttribute("book",bookService.findBookById(id));
		return "updateBook";
	}
	@PostMapping("/updateBook")
	public String updateBook(Book book){
		bookService.updateBook(book);
		return "redirect:/books";
	}
	@GetMapping("/searchBooks")
	public String searchBooks(Book book,Model model){
		model.addAttribute("books",bookService.searchBooks(book));
		return "books";
	}
}
